package com.xframe.xdal.core.model.sqlbuilder.proc;


import com.xframe.xdal.core.constant.DalConstants;
import com.xframe.xdal.core.model.mapping.IColumnMapping;
import com.xframe.xdal.core.model.sqlbuilder.BaseSqlBuilder;
import com.xframe.xdal.core.model.sqlbuilder.BuilderContext;
import com.xframe.xdal.core.model.sqlbuilder.SqlExpression;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：根据主键判断记录是否存在
 * 创建人：xufeng
 * 创建时间：2022/10/10 17:53
 *
 * @version 1.0
 **/
public class ExistsSqlBuilder extends BaseSqlBuilder {

    /**
     * sql 语句
     * @return
     */
    public String getSQL(){
        return "select count(1) from %s where %s";
    }

    @Override
    public SqlExpression build(BuilderContext context) {
        List<Object> paramList = new ArrayList<>();
        IColumnMapping pkFirst = context.findPkFirst();
        paramList.add(context.getData().getObjectFieldValue(pkFirst.getFieldName()));
        StringBuilder builder = new StringBuilder();
        builder.append(context.getNameConvert().toName(pkFirst.getName())).append(DalConstants.SQL_EQUAL)
                .append(DalConstants.SQL_PLACE_HOlDER);
        String isExistSql = String.format(getSQL(),context.getNameConvert().toName(context.getTableInfo().getName()), builder);
        return new SqlExpression(isExistSql,paramList,context.getDataSourceTypeEnums());
    }
}
